package maple.thelittleredbook.interaction.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.common.dto.ApiResponse;
import maple.thelittleredbook.common.service.AuthService;
import maple.thelittleredbook.interaction.dto.CommentCreateRequestDTO;
import maple.thelittleredbook.interaction.dto.CommentListResponse;
import maple.thelittleredbook.interaction.service.AsyncUserBehaviorService;
import maple.thelittleredbook.interaction.service.CommentService;
import maple.thelittleredbook.interaction.service.LikeService;
import maple.thelittleredbook.logging.annotation.SystemLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 交互控制器
 * 负责点赞、评论、点踩等用户交互功能
 */
@Slf4j
@RestController
@RequestMapping("/api/interactions")
public class InteractionController {

    private final AsyncUserBehaviorService asyncUserBehaviorService;
    private final CommentService commentService;
    private final AuthService authService;
    private final LikeService likeService;

    @Autowired
    public InteractionController(AsyncUserBehaviorService asyncUserBehaviorService,
                                 CommentService commentService,
                                 AuthService authService, LikeService likeService) {
        this.asyncUserBehaviorService = asyncUserBehaviorService;
        this.commentService = commentService;
        this.authService = authService;
        this.likeService = likeService;
    }

    /**
     * 点赞/取消点赞切换（自旋）
     * 支持内容和评论的点赞
     */
    @PostMapping("/like/toggle")
    @SystemLog(operation = "点赞切换")
    public ResponseEntity<ApiResponse<String>> toggleLike(
            @RequestParam Long targetId,
            @RequestParam String targetType) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 参数验证
        if (targetId == null) {
            return ResponseEntity.ok(ApiResponse.fail("目标ID不能为空"));
        }

        if (!"CONTENT".equals(targetType) && !"COMMENT".equals(targetType)) {
            return ResponseEntity.ok(ApiResponse.fail("目标类型只能是CONTENT或COMMENT"));
        }

        log.info("用户点赞切换请求，用户ID: {}, 目标ID: {}, 目标类型: {}", userId, targetId, targetType);

        // 同步处理点赞切换，获取最终状态
        boolean isLiked = likeService.toggleLike(userId, targetId, targetType);

        // 触发异步用户行为处理（在事务提交后执行）
        likeService.triggerAsyncBehaviorProcessing(userId, targetId, targetType, isLiked);

        // 根据最终状态返回明确的消息
        String action = isLiked ? "点赞成功" : "取消点赞成功";
        String targetName = "CONTENT".equals(targetType) ? "内容" : "评论";
        String message = action + "，" + targetName + "ID: " + targetId;

        return ResponseEntity.ok(ApiResponse.success(message));
    }

    /**
     * 点踩操作
     * 只支持内容点踩，每个内容只能点踩一次
     */
    @PostMapping("/dislike")
    @SystemLog(operation = "点踩内容")
    public ResponseEntity<ApiResponse<String>> dislikeContent(@RequestParam Long contentId) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 参数验证
        if (contentId == null) {
            return ResponseEntity.ok(ApiResponse.fail("内容ID不能为空"));
        }

        log.info("用户点踩内容请求，用户ID: {}, 内容ID: {}", userId, contentId);

        // 异步处理点踩行为
        asyncUserBehaviorService.processDislikeBehaviorAsync(userId, contentId);

        return ResponseEntity.ok(ApiResponse.success("点踩操作已提交，正在处理中"));
    }

    /**
     * 创建评论
     * 同步操作，直接返回结果
     */
    @PostMapping("/comments")
    @SystemLog(operation = "创建评论")
    public ResponseEntity<ApiResponse<String>> createComment(
            @Valid @RequestBody CommentCreateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户创建评论请求，用户ID: {}, 内容ID: {}, 评论内容长度: {}",
                userId, requestDTO.getContentId(),
                requestDTO.getCommentText() != null ? requestDTO.getCommentText().length() : 0);

        // 同步创建评论
        commentService.createComment(
                requestDTO.getContentId(),
                userId,
                requestDTO.getCommentText()
        );

        return ResponseEntity.ok(ApiResponse.success("评论创建成功"));
    }

    /**
     * 删除评论
     * 用户只能删除自己的评论，管理员可以删除任意评论
     */
    @DeleteMapping("/comments/{commentId}")
    @SystemLog(operation = "删除评论")
    public ResponseEntity<ApiResponse<String>> deleteComment(@PathVariable Long commentId) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 获取当前用户权限
        boolean isAdmin = authService.isCurrentUserAdmin();

        log.info("用户删除评论请求，用户ID: {}, 评论ID: {}, 是否管理员: {}", userId, commentId, isAdmin);

        // 同步删除评论
        boolean deleted = commentService.deleteComment(commentId, userId, isAdmin);

        if (deleted) {
            String action = isAdmin ? "管理员删除评论成功" : "评论删除成功";
            return ResponseEntity.ok(ApiResponse.success(action));
        } else {
            return ResponseEntity.ok(ApiResponse.fail("评论删除失败，可能评论不存在或无权限删除"));
        }
    }

    /**
     * 获取评论列表
     * 分页获取指定内容的评论列表
     */
    @GetMapping("/comments")
    @SystemLog(operation = "获取评论列表")
    public ResponseEntity<ApiResponse<CommentListResponse>> getCommentList(
            @RequestParam Long contentId,
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "orderBy", required = false) String orderBy) {

        // 获取当前用户ID
        Long currentUserId = authService.getCurrentUserId();

        // 参数验证
        if (contentId == null) {
            return ResponseEntity.ok(ApiResponse.fail("内容ID不能为空"));
        }

        log.info("查询评论列表，内容ID: {}, 当前用户ID: {}, 页码: {}, 大小: {}, 排序: {}",
                contentId, currentUserId, page, size, orderBy);

        // 查询评论列表
        CommentListResponse response = commentService.getCommentList(
                page, size, contentId, orderBy, currentUserId);

        return ResponseEntity.ok(ApiResponse.success("查询成功", response));
    }

    /**
     * 查询点赞状态
     * 用于前端判断是否已点赞
     */
    @GetMapping("/like/status")
    @SystemLog(operation = "查询点赞状态")
    public ResponseEntity<ApiResponse<Boolean>> getLikeStatus(
            @RequestParam Long targetId,
            @RequestParam String targetType) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 参数验证
        if (targetId == null) {
            return ResponseEntity.ok(ApiResponse.fail("目标ID不能为空"));
        }

        if (!"CONTENT".equals(targetType) && !"COMMENT".equals(targetType)) {
            return ResponseEntity.ok(ApiResponse.fail("目标类型只能是CONTENT或COMMENT"));
        }

        log.debug("查询点赞状态，用户ID: {}, 目标ID: {}, 目标类型: {}", userId, targetId, targetType);

        // 查询点赞状态
        boolean isLiked = asyncUserBehaviorService.getLikeStatus(userId, targetId, targetType) != null;

        return ResponseEntity.ok(ApiResponse.success("查询成功", isLiked));
    }
}